<?php
// +----------------------------------------------------------------------
// | OneThink [ WE CAN DO IT JUST THINK IT ]
// +----------------------------------------------------------------------
// | Copyright (c) 2013 http://www.onethink.cn All rights reserved.
// +----------------------------------------------------------------------
// | Author: huajie <banhuajie@163.com>
// +----------------------------------------------------------------------

namespace Admin\Controller;

/**
 * 行为控制器
 * @author huajie <banhuajie@163.com>
 */
class RelationController extends AdminController {
    /**
     * @author Scor
     * 业务信息
     */
    public function index(){
        $phone = I('user_phone');
        $saler = I('saler');
        $street = I('street');
        $realname = I('realname');
        $shop = I('shop');
        $map="";
        if ($phone) {
            $map['phone']=array('like','%'.$phone.'%');
        }
        if ($realname) {
            $map['realName']=array('like','%'.$realname.'%');
        }
        if ($saler) {
            $salerName['sname']=array('like','%'.$saler.'%');
            $resultUid=M("relationship")->where($salerName)->getField("uid",true);
            $map['id']=array("in",$resultUid);
        }
        if ($street) {
            $map['street']=array('like','%'.$street.'%');
        }
        if ($shop) {
            $map['shopName']=array('like','%'.$shop.'%');
        }
        $customersList = $this->listsM('buyers',$map,"id asc");
        if($customersList){
            for($i=0;$i<count($customersList);$i++){
                $map2['uid']=$customersList[$i]['id'];
                $res =M('relationship')->where($map2)->find();
                if($res){
                    $customersList[$i]['sname']=$res['sname'];
                }else{
                    $customersList[$i]['sname']="";
                }
            }
        }
        $this->assign("buyers",$customersList);
        $this->display();
    }
    public function export(){
        $sql = " select id,realName,phone,city,street,shopName,amount,from_unixtime(createdate) from gr_buyers  where 1=1 ";
        $phone = I('user_phone');
        $saler = I('saler');
        $street = I('street');
        $realname = I('realname');
        $shop = I('shop');
        $map = "";

        if ($phone) {
            $sql .= " and phone like '%" . $phone . "%'";
        }
        if ($realname) {
            $sql .= " and realName like '%" . $realname . "%'";
        }
        if ($saler) {
            $salerName['sname']=array('like','%'.$saler.'%');
            $resultUid=M("relationship")->where($salerName)->getField("uid",true);
            $uidstr = '(';
            for($i=0;$i<count($resultUid);$i++){
                if($i==0){
                    $uidstr.=$resultUid[$i];
                }else{
                    $uidstr.=','.$resultUid[$i];
                }

            }
            $uidstr.=')';
            $sql .= " and id in " . $uidstr . "";
        }
        if ($street) {
            $sql .= " and street like '%" . $street . "%'";

        }
        if ($shop) {
            $sql .= " and shopName like '%" . $shop . "%'";
        }
        $data = M('Buyers')->query($sql);
        if($data){
            for($i=0;$i<count($data);$i++){
                $map2['uid']=$data[$i]['id'];
                $res =M('relationship')->where($map2)->find();
                if($res){
                    $data[$i]['sname']=$res['sname'];
                }else{
                    $data[$i]['sname']="";
                }
            }
        }
        if ($data) {
            $orderTable = M('order');
            $data1 = array('is_export' => 1);

            $args = array_map(function($src){
                return $src['orderid'];}, $data);
            $map['orderid']  = array('in',$args);
            $result = $orderTable->where($map)->setField($data1);
            //导入PHPExcel类库，因为PHPExcel没有用命名空间，只能inport导入
            import("Org.Util.PHPExcel");
            import("Org.Util.PHPExcel.Writer.Excel5");
            import("Org.Util.PHPExcel.IOFactory.php");

            $filename = "output_order_excel";
            $headArr = array("编号","客户姓名","手机号","城市","街道","店铺","余额","创建时间","业务员");
            $this->getExcel($filename, $headArr, $data,null);
        }else{
            $this->error("没有可导出的数据");
        }

    }
    private function getExcel($fileName, $headArr, $data, $title) {
        //对数据进行检验
        if (empty($data) || !is_array($data)) {
            //die("data must be a array");
        }
        //检查文件名
        if (empty($fileName)) {
            exit;
        }
        // H:i:s
        $date = date("Y_m_d_H_i_s", time());
        //$date = date("Y_m_d",time());
        $fileName .= "_{$date}.xls";

        //创建PHPExcel对象，注意，不能少了\
        $objPHPExcel = new \PHPExcel();
        $objProps = $objPHPExcel->getProperties();

        //第一列设置报表时间范围
        $key = ord("A");
        $colum = chr($key);
        $objPHPExcel->setActiveSheetIndex(0)->setCellValue($colum . '1', $title);
        //第二列设置报表列头
        $key = ord("A");
        foreach ($headArr as $v) {
            $colum = chr($key);
            $objPHPExcel->setActiveSheetIndex(0)->setCellValue($colum . '2', $v);
            $objPHPExcel->getActiveSheet()->getStyle($colum . '2')->getFont()->setBold(true);
            $key += 1;
        }
        $column = 3;
        $objActSheet = $objPHPExcel->getActiveSheet();
        foreach ($data as $key => $rows) { //行写入
            $span = ord("A");
            foreach ($rows as $keyName => $value) {// 列写入
                $j = chr($span);
                $objActSheet->setCellValue($j . $column, $value);
                $span++;
            }
            $column++;
        }
        $objActSheet->getColumnDimension('A')->setWidth(5);
        $objActSheet->getColumnDimension('B')->setWidth(16);
        $objActSheet->getColumnDimension('C')->setWidth(16);
        $objActSheet->getColumnDimension('D')->setWidth(10);
        $objActSheet->getColumnDimension('E')->setWidth(25);
        $objActSheet->getColumnDimension('F')->setWidth(20);
        $objActSheet->getColumnDimension('G')->setWidth(5);
        $objActSheet->getColumnDimension('H')->setWidth(20);
        $objActSheet->getColumnDimension('I')->setWidth(10);
        $objActSheet->getColumnDimension('J')->setWidth(60);
        $objActSheet->getColumnDimension('K')->setWidth(80);
        $fileName = iconv("utf-8", "gb2312", $fileName);
        //重命名表
        // $objPHPExcel->getActiveSheet()->setTitle('test');
        //设置活动单指数到第一个表,所以Excel打开这是第一个表
        $objPHPExcel->setActiveSheetIndex(0);
        header('Content-Type: application/vnd.ms-excel');
        header("Content-Disposition: attachment;filename=\"$fileName\"");
        header('Cache-Control: max-age=0');

        $objWriter = \PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel5');
        $objWriter->save('php://output'); //文件通过浏览器下载
        exit;
    }
    public function details(){
        $detail=I();
        $map["uid"]=$detail['uid'];
        $map["status"]=3000;
        $data['id']=$detail['uid'];
        $info=M("buyers")->where($data)->find();
        $sum=M("order")->where($map)->sum("amount");
        $res2=M('relationship')->where($map)->find();
        $sList=M('sale_man')->select();
        //订单详细
        $ordermMap["uid"]=$detail['uid'];
        $res=$this->listsM('order',$ordermMap,"");
        if($res2){
            $info['sname']=$res2['sname'];
        }else{
            $info['sname']="";
        }
        if($sum==NULL||$sum==0||$sum==""){
            $info['sum']=0;
        }else{
            $info['sum']=$sum;
        }

        sg_int_to_string_order($res);
        $this->assign("orderLists",$res);
        $this->relation=$info;
        $this->assign("sales",$sList);
        $this->display();
    }
    public function changeSname(){
        $map["uid"]=I("uid");
        $data["sname"]=I("sname");
        $data["sid"]=I("sid");
        $res=M("relationship")->where($map)->find();
        if($res){
            $result=D("relationship")->where($map)->save($data);
        }else{
            $data['uid']=I("uid");
            $result=D("relationship")->add($data);
        }
        if($result){
            echo "修改成功";
        }else{
            echo "修改成功，但没有变化";
        }
    }
    public function changePhone(){
        $map["uid"]=I("uid");
        $data["phone"]=I("phone");
        $result=D("buyers")->where($map)->save($data);
        if($result){
            echo "修改成功";
        }else{
            echo "修改成功，但没有变化";
        }
    }
    public function data(){
        $falg = I('flag');
        if ($falg=="count"){
            $res = M("order")->query("SELECT  toName,sum,count from (SELECT toName,sum(amount) as sum ,count(*) as count FROM gr_order GROUP BY uid) as result order by count desc limit 20");
        }else{
            $res=M("order")->query("SELECT  toName,sum,count from (SELECT toName,sum(amount) as sum ,count(*) as count FROM gr_order GROUP BY uid) as result order by sum desc limit 20");
        }
        $sum=M("order")->sum('amount');
        $this->assign("buyers",$res);
        $this->sum=$sum;
        $this->display();
    }
    //余额流水展示
    public function amountFlow2(){
        $userid = $_REQUEST['uid'];
        $nickname = $_REQUEST['nickname'];
        $map["uid"]=$userid;
        $list = $this-> listsM("amount_flow",$map,'createtime desc');
        $this->assign('nickname',$nickname);
        $this->assign('amountFlows', $list);
        $this->display();
    }
    public function returnAmount(){
        $map["id"]=I("uid");
        $amount=I("amount");
        $mark=I("mark");
        $data['nickname']=get_nickname();
        $data['action']=$mark."变动".$amount;
        $data['objectuid']=$map["id"];
        $data['creattime']=time();
        $detail="(".$mark.")后台人工变动";
        if($amount > 0){
            $action = "incre";
        }else{
            $action = "decre";
        }
        $this->amountFlow(I("uid"),abs($amount),$action,$detail);
        if(D('buyers')->where($map)->setInc('amount',$amount)){
            echo "修改成功";
        }else{
            echo "修改失败";
        }

    }
}
